package cn.iocoder.yudao.module.mqtt.service.devicelatestflow;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.module.mqtt.controller.admin.littree.vo.LisToken;
import cn.iocoder.yudao.module.mqtt.controller.admin.littree.vo.site.LisListVO;
import cn.iocoder.yudao.module.mqtt.controller.admin.littree.vo.site.LisShunVO;
import cn.iocoder.yudao.module.mqtt.controller.admin.littree.vo.site.LisSubVO;
import cn.iocoder.yudao.module.mqtt.controller.admin.littree.vo.site.res.LisListRes;
import cn.iocoder.yudao.module.mqtt.controller.admin.littree.vo.site.res.LisRes;
import cn.iocoder.yudao.module.mqtt.dal.dataobject.device.DeviceDO;
import cn.iocoder.yudao.module.mqtt.dal.dataobject.devicelatestlog.DeviceLatestLogDO;
import cn.iocoder.yudao.module.mqtt.dal.mysql.devicelatestlog.DeviceLatestLogMapper;
import cn.iocoder.yudao.module.mqtt.util.HttpSysUtil;
import cn.iocoder.yudao.module.mqtt.util.LisTreeUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.esotericsoftware.minlog.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import cn.iocoder.yudao.module.mqtt.controller.admin.devicelatestflow.vo.*;
import cn.iocoder.yudao.module.mqtt.dal.dataobject.devicelatestflow.DeviceLatestFlowDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.mqtt.dal.mysql.devicelatest.DeviceLatestFlowMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.mqtt.enums.ErrorCodeConstants.*;

/**
 * 设备最新信息 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class DeviceLatestFlowServiceImpl implements DeviceLatestFlowService {

    @Resource
    private DeviceLatestFlowMapper deviceLatesFlowtMapper;
    @Autowired
    private DeviceLatestLogMapper deviceLatestLogMapper;

    @Override
    public Long createDeviceLatest(DeviceLatestFlowSaveReqVO createReqVO) {
        // 插入
        DeviceLatestFlowDO deviceLatest = BeanUtils.toBean(createReqVO, DeviceLatestFlowDO.class);
        deviceLatesFlowtMapper.insert(deviceLatest);
        // 返回
        return deviceLatest.getId();
    }

    @Override
    public void updateDeviceLatest(DeviceLatestFlowSaveReqVO updateReqVO) {
        // 校验存在
//        validateDeviceLatestExists(updateReqVO.getId());
        // 更新
        DeviceLatestFlowDO updateObj = BeanUtils.toBean(updateReqVO, DeviceLatestFlowDO.class);
        deviceLatesFlowtMapper.updateById(updateObj);
    }

    @Override
    public void updateDeviceLatest(DeviceLatestFlowDO latestDO) {
        deviceLatesFlowtMapper.updateById(latestDO);
    }

    @Override
    public void updateDeviceLatestByGetewayId(List<DeviceLatestFlowDO> doList) {
        deviceLatesFlowtMapper.updateBatch(doList);

    }

    @Override
    public DeviceLatestFlowDO saveWater(DeviceDO deviceDO) {
        LisToken lis = LisTreeUtil.getToken();
        //获取水量
        LisListRes<LisShunVO> water = LisTreeUtil.getWater(lis.getAccess_token(), deviceDO.getGatewayId());
        if( water.getData().size()>0){
            LisShunVO lisShunVO = water.getData().get(0);
            DeviceLatestFlowDO lastestDO = new DeviceLatestFlowDO();
            lastestDO.setGatewayId(deviceDO.getGatewayId());
            lastestDO.setLisDay(lisShunVO.get日产水量());
            lastestDO.setLisAll(lisShunVO.get总产水量());
            lastestDO.setLisYear(lisShunVO.get年产水量());
            lastestDO.setLisTime(LisTreeUtil.convertToUtcLocalDateTime(lisShunVO.getTime()));
            lastestDO.setListMonth(lisShunVO.get月产水量());
            lastestDO.setId(deviceDO.getId());
            lastestDO.setDeviceId(deviceDO.getId());
            lastestDO.setDeviceKey(deviceDO.getDeviceKey());
            lastestDO.setDeviceName(deviceDO.getCountryName());
            lastestDO.setUpdater("SYS");
            lastestDO.setUpdateTime(LocalDateTime.now());
            lastestDO.setCreator("SYS");
            lastestDO.setDeleted(false);
            lastestDO.setCreateTime(LocalDateTime.now());
            deviceLatesFlowtMapper.insertOrUpdate(lastestDO); //水量
            return lastestDO;
        }else{
            Log.info(deviceDO.getGatewayId()+ "  ------  " + "没有数据");
        }


        return null;
    }

    @Override
    public DeviceLatestFlowDO saveWaterSun(DeviceDO deviceDO) {
        LisToken lis = LisTreeUtil.getToken();
        LisRes<LisListVO> resVO =  LisTreeUtil.getListMin10(deviceDO.getGatewayId(), lis.getAccess_token());
        LisListVO data = resVO.getData();
        if(data.getList().size() > 0){
            DeviceLatestFlowDO lastestDO = new DeviceLatestFlowDO();
            LisSubVO lisSubVO = data.getList().get(data.getList().size()-1);
            String all = ObjectUtil.isNotEmpty(lisSubVO.get产水累积量())? String.valueOf(lisSubVO.get产水累积量()) : "0";
            String sun = ObjectUtil.isNotEmpty(lisSubVO.get产水流量())? String.valueOf(lisSubVO.get产水流量()) : "0";
            lastestDO.setLisSunAll(all);
            lastestDO.setLisSun(sun);
            lastestDO.setLisSunTime(LisTreeUtil.convertToUtcLocalDateTime(lisSubVO.getTime()));
            lastestDO.setId(deviceDO.getId());
            lastestDO.setUpdater("SYS");
            lastestDO.setUpdateTime(LocalDateTime.now());
            deviceLatesFlowtMapper.updateById(lastestDO); //水量
            return lastestDO;
        }
        return null;
    }

    @Override
    public DeviceLatestFlowDO saveWaterHourSun(DeviceDO deviceDO) {
        LisToken lis = LisTreeUtil.getToken();
        String beginDate = LisTreeUtil.getLastHourBegin();
        String endDate = LisTreeUtil.getLastHourEnd();
        System.out.println("开始时间：" + beginDate + "  结束时间：" + endDate);
       // String dayBegin = LisTreeUtil.getDayBegin();

        LisRes<LisListVO> hourVO =  LisTreeUtil.getListLastHour(beginDate, endDate,lis.getAccess_token(),deviceDO.getGatewayId());
        LisListVO data2 = hourVO.getData();
        if(data2.getList().size() > 0){
            DeviceLatestFlowDO lastestDO = new DeviceLatestFlowDO();
            LisSubVO lisSubVO = data2.getList().get(data2.getList().size()-1);
            String sun = ObjectUtil.isNotEmpty(lisSubVO.get产水流量())? String.valueOf(lisSubVO.get产水流量()) : "0";
            lastestDO.setHourBegin(beginDate);
            lastestDO.setHourEnd(beginDate);
            lastestDO.setLisSunHour(sun);
            lastestDO.setLisSunTime(LisTreeUtil.convertToUtcLocalDateTime(lisSubVO.getTime()));
            lastestDO.setId(deviceDO.getId());
            lastestDO.setUpdater("SYS");
            lastestDO.setUpdateTime(LocalDateTime.now());
            deviceLatesFlowtMapper.updateById(lastestDO); //水量
            return lastestDO;
        }
        return null;
    }

    @Override
    public Integer uploadJCJ(DeviceLatestFlowDO deviceLatestDO, Long logId) {
        String req = "https://cxqjgs.dcyun.com:38121/api/upload/uploadPlantWaterRealTimeSupply";
//        Map<String, String> map = new HashMap<>();
//        map.put("userName", ":SXXC6753");
//        map.put("userAuth", "DGdBTS6S");
//        map.put("plantName", );
//        map.put("inspectTime", );
//        map.put("supplyFlow", deviceLatestDO.getLisSun());
//        map.put("totalSupplyQuantity", deviceLatestDO.getLisSunAll());
//        System.out.println(JSON.toJSONString(map));

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd/HH:mm");
        LocalDateTime now = LocalDateTime.now();
        // 3. 格式化时间并输出
        String currentTime = now.format(formatter);
        String supplyFlow = "0";
        String lisDay ="0";
       try {
           currentTime = ObjectUtil.isEmpty(deviceLatestDO.getHourEnd())? currentTime : formatD(deviceLatestDO.getHourEnd());
           supplyFlow = ObjectUtil.isEmpty(deviceLatestDO.getLisSun())? "0": deviceLatestDO.getLisSun();
           lisDay = ObjectUtil.isEmpty(deviceLatestDO.getLisDay())? "0": deviceLatestDO.getLisDay();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String params = "{\n" +
                "\"userName\":\"SXXC6753\",\n" +
                "\"userAuth\":\"DGdBTS6S\",\n" +
                "\"plantName\":\""+deviceLatestDO.getDeviceName()+"\",\n" +
                "\"inspectTime\":\""+currentTime+"\",\n" +
                "\"supplyFlow\":\""+supplyFlow+"\",\n" +
                "\"totalSupplyQuantity\":\""+lisDay+"\"\n" +
                "}";
        String res = HttpSysUtil.doPost(req, params, null);
        if(deviceLatestDO.getDeviceName().contains("东山")){
            System.out.println(res);
        }

        DeviceLatestLogDO logDO = new DeviceLatestLogDO();
        logDO.setLisSunTime(deviceLatestDO.getLisSunTime());
        logDO.setLisSunHour(deviceLatestDO.getLisSunHour());
        logDO.setHourEnd(deviceLatestDO.getHourEnd());
        logDO.setHourBegin(deviceLatestDO.getHourBegin());
        logDO.setLisDay(deviceLatestDO.getLisDay());
        logDO.setLisSun(deviceLatestDO.getLisSun());

        JSONObject jsonObject = JSONObject.parseObject(res);
        try{
            // 获取status字段的值
            int status = jsonObject.getIntValue("status");
            String resStatus = status == 0 ? "1" : "0";
            logDO.setResponseStatus(resStatus);//0 否， 1-成功

            if("0".equals(resStatus) ){
                System.out.println("失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logDO.setSendStatus("0");
        }
        logDO.setSendStatus("1");// 0 待发送  1 已发送

        logDO.setDeviceId(deviceLatestDO.getDeviceId());
        logDO.setDeviceName(deviceLatestDO.getDeviceName());
        logDO.setDeviceKey(deviceLatestDO.getDeviceKey());
        logDO.setGatewayId(deviceLatestDO.getGatewayId());
        logDO.setRequestType("0");//水量
        logDO.setRequestBody(params);
        logDO.setResponseBody(res.length()>200? res.substring(0,190) : res);

        logDO.setDeleted(false);
        logDO.setUpdater("SYS");
        logDO.setId(logId);
        logDO.setCreator("SYS");
        logDO.setUpdateTime(LocalDateTime.now());
        deviceLatestLogMapper.insertOrUpdate(logDO);

        return jsonObject.getIntValue("status");
    }

    @Override
    public void deleteDeviceLatest(Long id) {
        // 校验存在
        validateDeviceLatestExists(id);
        // 删除
        deviceLatesFlowtMapper.deleteById(id);
    }

    @Override
        public void deleteDeviceLatestListByIds(List<Long> ids) {
        // 校验存在
        validateDeviceLatestExists(ids);
        // 删除
        deviceLatesFlowtMapper.deleteByIds(ids);
        }

    private void validateDeviceLatestExists(List<Long> ids) {
        List<DeviceLatestFlowDO> list = deviceLatesFlowtMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(DEVICE_LATEST_NOT_EXISTS);
        }
    }

    private void validateDeviceLatestExists(Long id) {
        if (deviceLatesFlowtMapper.selectById(id) == null) {
            throw exception(DEVICE_LATEST_NOT_EXISTS);
        }
    }

    @Override
    public DeviceLatestFlowDO getDeviceLatest(Long id) {
        return deviceLatesFlowtMapper.selectById(id);
    }

    @Override
    public DeviceLatestFlowDO getDeviceLatestByGatewayId(String getewatId) {
        return deviceLatesFlowtMapper.selectOne("gateway_id", getewatId);
    }

    @Override
    public DeviceLatestFlowDO getDeviceKey(String dKey) {
        return deviceLatesFlowtMapper.selectOne("device_key", dKey);
    }

    @Override
    public PageResult<DeviceLatestFlowDO> getDeviceLatestPage(DeviceLatestFlowPageReqVO pageReqVO) {
        return deviceLatesFlowtMapper.selectPage(pageReqVO);
    }

    @Override
    public List<DeviceLatestFlowDO> getList(DeviceLatestFlowReqVO reqVO) {
        return deviceLatesFlowtMapper.selectList(reqVO);
    }



    public static String formatD(String hourEndStr ){
        System.out.println("--" + hourEndStr);
        if(ObjectUtil.isEmpty(hourEndStr)){
            return "";
        }
        // 定义原始格式的解析器
        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 解析为LocalDateTime对象
        LocalDateTime dateTime = LocalDateTime.parse(hourEndStr, inputFormatter);
        // 定义目标格式（yyyy-MM-dd/HH:mm）
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd/HH:mm");
        // 转换格式并输出
        String convertedTime = dateTime.format(outputFormatter);
        return  convertedTime;
    }

    public static void main(String[] args) {
        System.out.println(formatD("2025-08-22 20:00:00"));
    }
}